package com.relife.core.easyui;

import com.relife.common.http.BrowserUtils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;




public class PrintTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String code;
	private String url;

	@Override
	public int doStartTag() throws JspTagException {
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			JspWriter out = this.pageContext.getOut();
			StringBuffer sb = new StringBuffer();
			sb.append(this.getHtml());
			out.print(sb);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}

	private StringBuffer getHtml() {
		StringBuffer sb = new StringBuffer("");
		boolean isIE = BrowserUtils.isIE((HttpServletRequest) this.pageContext.getRequest());
		if (isIE) {
			sb.append("<OBJECT id=\"wb\" name=\"wb\" height=0 width=0 classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></OBJECT>\n");
		}
		sb.append("<script type=\"text/javascript\">\n");
		sb.append("function printPage(obj){\n");
		sb.append("$(obj).hide();\n");
		if (isIE) {
			sb.append(" var wb=document.getElementById('wb');\n");
			sb.append(" wb.ExecWB(7,1);\n");
		} else {
			sb.append(" self.print()\n");
		}
		sb.append(" printTimes();\n");
		sb.append("$(obj).show();\n");
		sb.append("}\n");

		sb.append("function printTimes(){\n");
		sb.append(" $.post('" + url + "',{'code':'" + code + "'},function(data){\n");
		sb.append("   if(data.success){\n");
		if (isIE) {
			sb.append("	  self.close();\n");
		} else {
			sb.append("	 frameElement.api.close();\n");
		}
		sb.append("   }\n");
		sb.append(" },'json');\n");
		sb.append("}\n");

		sb.append("</script>\n");
		
		sb.append("<div class=\"prntDiv\"><input onclick='printPage(this)' class='printBut' type='button' value='打印'></div>\n");
		return sb;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}
